import { defineComponent, onMounted, onBeforeUnmount, PropType, ref, computed, nextTick } from 'vue'
import { ElButton } from 'element-plus'
import '@/styles/intercom.css'
import phone from '@/assets/phone.png'
import phone2 from '@/assets/404.png'
import { avRequest } from '@/api/gps/jt808/jt1078'
//tool
import { handIntercomStart, handIntercomStop, recordStartStop } from '@/utils/gps/jt1078/intercom'
import moment from 'moment/moment'
import { ElMessage } from 'element-plus'
import Recorder from '@/utils/gps/audio/index'

export default defineComponent({
  name: 'Intercom',
  props: {
    equipment: {
      type: Object as PropType<{ imei: string; channel: number; name: string } | any>,
      required: true
    }
  },
  setup(prop) {
    let timer: any
    const time = ref(0)
    const animationRef = ref()
    const running = ref(false)
    let sMedia: any = undefined
    let recorder: Recorder
    let cvsTool

    const formatTime = computed(() => {
      return moment.utc(moment.duration(time.value, 'seconds').asMilliseconds()).format('HH:mm:ss')
    })

    onMounted(() => {
      init()
    })
    // onBeforeUnmount(() => {
    //   sMedia = undefined
    // })

    function init() {
      nextTick(() => {
        openConnection()
        animationRef.value.className = 'loader'

        cvsTool = initCanvas()
      })
      // setTimeout(() => {
      // }, 1000)
    }

    function openConnection() {
      // if (!sMedia) {
      //   return
      // }
      handIntercomStart(prop.equipment.imei, prop.equipment.channel, sMedia)
        .then(() => {
          console.log('startd')
          running.value = true
          connectionSuccessful()
        })
        .catch((e) => {
          console.log(e)
          ElMessage.error(e)
        })
    }

    function connectionSuccessful() {
      timer = setInterval(() => {
        time.value++
      }, 1000)
      document.addEventListener("keypress", (e)=>{
        console.log(e.key)
      })
    }

    function hang() {
      if (running.value) {
        handIntercomStop(prop.equipment.imei, prop.equipment.channel).then(() => {
          console.log('stoped')
          running.value = false
          clearInterval(timer)
          time.value = 0
          animationRef.value.className = 'none'
        })
      } else {
        init()
      }
    }
    function record() {
      if (running.value) {
        recorder = recordStartStop(true)

        cvsTool.draw()
      }

    }



    function initCanvas(){
      const cvs: HTMLCanvasElement = document.querySelector('#audio_canvas')!
      const ctx = cvs.getContext('2d')!

      function draw(){
        requestAnimationFrame(draw)
        const { width, height } = cvs
        ctx.clearRect(0, 0, width, height)

        let dataArray = recorder.getRecordAnalyseData(),
            bufferLength = dataArray.length;
        // 填充背景色
        ctx.fillStyle = 'rgb(255,255,255)';
        ctx.fillRect(0, 0, width, height);

        // 设定波形绘制颜色
        ctx.lineWidth = 2;
        ctx.strokeStyle = 'rgb(0, 0, 0)';

        ctx.beginPath();

        let sliceWidth = width * 1.0 / bufferLength, // 一个点占多少位置，共有bufferLength个点要绘制
            x = 0;          // 绘制点的x轴位置

        for (let i = 0; i < bufferLength; i++) {
          const v = dataArray[i] / 128.0;
          const y = v * height / 2;

          if (i === 0) {
            // 第一个点
            ctx.moveTo(x, y);
          } else {
            // 剩余的点
            ctx.lineTo(x, y);
          }
          // 依次平移，绘制所有点
          x += sliceWidth;
        }

        ctx.lineTo(width, height / 2);
        ctx.stroke();
      }

      return {draw}
    }

    return () => (
        <div class="intercom">
          <p class="name">{prop.equipment.name}</p>
          <div class="animation">
            <div ref={animationRef} class="static" v-show={!running.value}></div>
            <canvas id="audio_canvas" width="200" height="50" v-show={running.value}></canvas>
          </div>
          <p class="time">{formatTime.value}</p>
          <div style="margin-bottom: 30px">
            <ElButton type="danger" circle class="phone" onClick={hang}>
              <img src={phone} alt="电话"></img>
            </ElButton>
            <ElButton type="danger" circle class="phone" onClick={record}>
              <img src={phone2} alt="电话1"></img>
            </ElButton>
          </div>

        </div>
    )
  }
})
